﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCore和EF使用CodeFirst生成数据库
{
    public class MyDbContext: DbContext
    {

        //
        public MyDbContext()
        {
            this.Database.EnsureCreated();
        }
        public DbSet<Person> Persons { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseMySql(
                @"Server=127.0.0.1;database=etwj2;uid=root;pwd=root");

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            var persons =modelBuilder.Entity<Person>();
            persons.ToTable("T_Persons");


            var users = modelBuilder.Entity<User>();
            users.ToTable("T_Users");

            var roles = modelBuilder.Entity<Role>();
            roles.ToTable("T_Roles");


            var userRoles = modelBuilder.Entity<UserRole>();
            userRoles.ToTable("T_UserRoles");

            userRoles.HasOne(e => e.Role).WithMany().HasForeignKey(e => e.RoleId).IsRequired();
            userRoles.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId).IsRequired();


        }
    }
}
